<template>
  <div style="padding: 0 15px;">
    <van-nav-bar
        title="完善用户信息"
        left-arrow
        @click-left="onClickLeft"
    />
    <div style="width: 100%;margin: 10px auto;">
      <el-upload
          align="left"
          class="avatar-uploader"
          style="text-align: center"
          action="http://localhost:10086/api/user/user/upload/uploadLocal"
          :show-file-list="false"
          :on-success="handleAvatarSuccess">
        <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>

    <van-action-sheet
        v-model="show1"
        :actions="actions1"
        description="请选择您的性别"
        cancel-text="取消"
        @select="onSelect1"
    />
    <van-cell-group>
      <van-field class="healthRecordBasicInfo" v-model="user.realName" label="真实姓名"
                 placeholder="请输入您的真实姓名" style="border-top: 1px solid #e5e5e5;"/>
      <van-field class="healthRecordBasicInfo" v-model="user.idCard" label="身份证号" @blur="card"
                 placeholder="请输入您的身份证号"/>
      <van-field
          readonly
          is-link
          class="healthRecordBasicInfo"
          v-model="user.gender"
          label="性别"
          placeholder="请选择您的性别"
          @click="show1 = true"
      />
      <van-field v-if="user.birthDate" class="healthRecordBasicInfo" v-model="user.birthDate" label="出生日期"
                 placeholder="请输入您的出生日期">
        <template #input>
          {{ user.birthDate | format('yyyy-MM-dd') }}
        </template>
      </van-field>
      <van-field class="healthRecordBasicInfo" v-model="user.currentAddress" label="现居地"
                 placeholder="请输入您的现居地"/>
    </van-cell-group>
    <div class="login-container" style="margin-top: 20px">
      <el-button type="primary" @click="onSubmit" style="width: 80%;margin: 10px auto;">确定</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "ImproveInformationView",
  data() {
    return {
      avatarUrl: '',
      user: {
        id: '',
        phoneNumber: '',
        password: '',
        realName: '',
        idCard: '',
        gender: '',
        birthDate: '',
        currentAddress: '',
        relationToSelf: '',
        privacyPolicyAgreed: '',
        userType: '',
        imageUrl: '',
      },
      show1: false,
      actions1: [
        {name: '男'},
        {name: '女'},
      ],
    }
  },
  created() {
    const token = JSON.parse(localStorage.getItem("token"));
    if (!token) {
      this.$message.error('请先登录');
      setTimeout(() => {
        this.$router.push({name: 'login'});
      });
    }
    // 设置全局默认请求头
    this.axios.defaults.headers.common['token'] = token;
    this.findUserInfo()
  },
  methods: {
    onSubmit() {
      this.axios.post(`http://localhost:10086/api/user/user/improveInformation`, this.user).then(res => {
        if (res.data.code == 200) {
          this.$message.success('完善用户信息成功');
          setTimeout(() => {
            this.$router.push({name: 'my'});
          });
        } else {
          this.$message.error('完善用户信息失败');
        }
      })
    },
    findUserInfo() {
      this.axios.get(`http://localhost:10086/api/user/user/findUserInfo`).then(res => {
        if (res.data.code == 200) {
          this.user = res.data.data
          this.avatarUrl = this.user.imageUrl
          console.log(this.user)
        } else {
          console.log(res);
        }
      })
    },
    card() {
      if (this.user.idCard.length && this.user.idCard.length === 18) {
        var year = this.user.idCard.substring(6, 10);
        var month = this.user.idCard.substring(10, 12);
        var day = this.user.idCard.substring(12, 14);
        this.user.birthDate = `${year}-${month}-${day}`
      }
    },
    onSelect1(item) {
      this.show1 = false;
      this.user.gender = item.name;
    },
    onClickLeft() {
      this.$router.push({name: 'my'})
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(file.raw);
      this.$message.success('上传成功')
      this.avatarUrl = URL.createObjectURL(file.raw)
      this.user.imageUrl = res.data
    },
  }
  ,
  filters: {
    format(value, arg) {
      function dateFormat(date, format) {
        if (typeof date === "string") {
          var mts = date.match(/(\/Date\((\d+)\)\/)/);
          if (mts && mts.length >= 3) {
            date = parseInt(mts[2]);
          }
        }
        date = new Date(date);
        if (!date || date.toUTCString() == "Invalid Date") {
          return "";
        }
        var map = {
          "M": date.getMonth() + 1, //月份
          "d": date.getDate(), //日
          "h": date.getHours(), //小时
          "m": date.getMinutes(), //分
          "s": date.getSeconds(), //秒
          "q": Math.floor((date.getMonth() + 3) / 3), //季度
          "S": date.getMilliseconds() //毫秒
        };
        format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
          var v = map[t];
          if (v !== undefined) {
            if (all.length > 1) {
              v = '0' + v;
              v = v.substr(v.length - 2);
            }
            return v;
          } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
          }
          return all;
        });
        return format;
      }

      return dateFormat(value, arg);

    }
  }
  ,
}
</script>

<style scoped>
.healthRecordBasicInfo {
  border-bottom: 1px solid #e5e5e5;
}

.avatar-uploader .el-upload {
  border: 1px dashed #000000;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  border: 1px dashed #000000;
  border-radius: 6px;

  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  border: 1px dashed #000000;
  border-radius: 6px;

  width: 100px;
  height: 100px;
  display: block;
}
</style>